<?php

namespace app\api\biz;

use app\common\biz\Biz;
use app\common\biz\list\Lists;
use app\common\biz\list\Search;
use app\common\enum\Code;
use app\common\model\biz\SysDictDetail;
use app\common\Result;
use Exception;
use think\db\exception\DbException;

class DictDetailBiz extends Biz
{

    public static function list(array $searchParams = []): DictDetailBiz
    {
        $search = new Search($searchParams);

        $lists = new Lists(new SysDictDetail(), $search);
        return self::success($lists->data());
    }

    public static function add(array $data): DictDetailBiz
    {
        try {
            $detail = SysDictDetail::where('dict_code', $data['dict_code'])
                ->where('name', $data['name'])
                ->where('status', 0)
                ->findOrEmpty();
            if (!$detail->isEmpty()) {
                return self::error('此字典详情标识已存在！');
            }

            $detail = SysDictDetail::create($data);
            return self::success($detail);
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    public static function edit(array $data): DictDetailBiz
    {
        if (!isset($data['id'])) {
            return self::errorByCode(Code::ParamsInvalid);
        }

        try {
            $detail = SysDictDetail::findOrEmpty($data['id']);
            if ($detail->isEmpty()) {
                return self::errorByCode(Code::DataNotFound);
            }
            $isExist = SysDictDetail::where('dict_code', $data['dict_code'])
                ->where('name', $data['name'])
                ->where('id', '<>', $data['id'])
                ->findOrEmpty();
            if (!$isExist->isEmpty()) {
                return self::error('此字典标识已存在！');
            }

            $isOk = $detail->save($data);
            return self::success($isOk);
        } catch (DbException $e) {
            Result::dbException($e->getData());
        } catch (Exception $e) {
            Result::httpException($e->getMessage());
        }
    }

    public static function del(string|array $ids): DictDetailBiz
    {
        $details = SysDictDetail::whereIn('id', $ids)->select();
        if ($details->isEmpty()) {
            return self::errorByCode(Code::DataNotFound);
        }

        foreach ($details as $detail) {
            $detail->delete();
        }

        return self::success();

    }
}